# coding=utf8
import re

# 生成sql语句
def get_info (course_string):
    time = re.search(r'^\d{1,2}', course_string).group()
    name = re.search(r'\D[^_]*', course_string).group()

    total = re.search(r'\(\S*\)', course_string).group().replace('(', '').replace(')', '')
    total_set = total.split(',')
    addr = re.search(r'\D*$', total_set[0]).group()
    room = total_set[1]
    teacher = total_set[2]
    start = re.findall(r'\d{1,2}', total_set[3])[0]
    if re.findall(r'\d{1,2}', total_set[3]).__len__() == 1:
        end = start
    else:
        end = re.findall(r'\d{1,2}', total_set[3])[1]
    sql = "INSERT INTO `swpu_course_info` VALUES ('NULL', '%s', '%s', '%s', '%s', '%s', '%s', '%s');" % (name, addr, room, time, teacher, start, end)
    return sql

# 获取要读取的文件列表集合
def get_file_list ():
    file_list = []
    fp = open('bjh/bjh.txt', 'r')
    while 1:
        line = fp.readline().strip()
        file_list.append(line + '.txt')
        if not line:
            break
        pass
    file_list.pop()
    fp.close()
    return file_list

# 获取文件中的内容
def get_file_content (file_name):
    file = 'db/' + file_name
    fp = open(file, 'r')
    all = fp.readlines()
    course_set = []
    for line in all:
        if re.search(r'\S', line):
            if re.search(r'\xc2\xa0', line):
                pass
            else:
                course_set.append(line.strip())
    fp.close()
    return course_set

# 获取课程信息总文件
def get_total_set():
    fp = open('db/total/total.txt', 'a')
    file_list = get_file_list()
    for file in file_list:
        for e in get_file_content(file):
            fp.write(e + '\n')
    fp.close()

fp = open('db/total/total.txt', 'r')
c_list = []
total = fp.readlines()
fp.close()
fp = open('total.sql', 'a')
for e in total:
    fp.write(str(get_info(e)) + '\n')